package com.haifeng.jupiter.common.datasource.aop;

import com.haifeng.jupiter.common.core.util.MessageUtils;
import com.haifeng.jupiter.common.datasource.annotation.OptimisticLockRetryAnnotation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * <p>
 *  乐观锁重试AOP
 * </p>
 *
 * @author: Haifeng
 * @date: 2020-08-15
 */
@Slf4j
@Aspect
@Component
@AllArgsConstructor
public class OptimisticLockRetryAop implements Ordered {

    private final MessageUtils messageUtils;

    @Pointcut("@annotation(com.haifeng.jupiter.common.datasource.annotation.OptimisticLockRetryAnnotation)")
    public void retryOnOptFailure() {}

    @Around("retryOnOptFailure()")
    public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method targetMethod = methodSignature.getMethod();
        OptimisticLockRetryAnnotation annotation = targetMethod.getAnnotation(OptimisticLockRetryAnnotation.class);
        Integer retryTimes = annotation.retryTimes();
        while (retryTimes > 0) {
            Thread.sleep(500);
            retryTimes--;
            try {
                return pjp.proceed();
            } catch (Exception e) {
                log.warn("{}乐观锁重试失败，剩余次数：{}",targetMethod,retryTimes);
            }
        }
        throw new OptimisticLockingFailureException("网络异常，请重新尝试");
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
